package com.itranswarp.learnjava.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserService {

    @Autowired
    private MailService mailService;

    //构造函数注入
    /*public UserService(@Autowired MailService mailService) {
        this.mailService = mailService;
    }
    */
    //赋值器（setter）注入
    public void setMailService(@Autowired MailService mailService)
    {
        this.mailService = mailService;
    }
    @Autowired
    private CartService cartService;

    public void setCartService(@Autowired CartService cartService) {
        this.cartService = cartService;
    }

    private List<User> users = new ArrayList<>(List.of( // users:
            new User(1, "bob@example.com", "password", "Bob"), // bob
            new User(2, "alice@example.com", "password", "Alice"), // alice
            new User(3, "tom@example.com", "password", "Tom"))); // tom

    //模拟数据
    private List<Goods> goodsList = new ArrayList<>(List.of(
            new Goods(1,1,"刮胡刀",1,90.0),
            new Goods(2,1,"洗发水",2,30.0),
            new Goods(3,1,"毛巾",3,10.0),
            new Goods(4,2,"刮胡刀",1,90.0),
            new Goods(5,3,"刮胡刀",1,90.0)
    ));

    public void printCartInfo(long userId){
        var userGoodsList = cartService.getUserGoods(userId,goodsList);
        if(userGoodsList!=null) {
            for (var goods :
                    userGoodsList) {
                System.out.println("商品名："+goods.getName()+"， 商品数量："+goods.getCount()+", 单价："+goods.getPrice());
            }
        }
    }

    public User login(String email, String password) {
        for (User user : users) {
            if (user.getEmail().equalsIgnoreCase(email) && user.getPassword().equals(password)) {
                mailService.sendLoginMail(user);
                return user;
            }
        }
        throw new RuntimeException("login failed.");
    }

    public User getUser(long id) {
        return this.users.stream().filter(user -> user.getId() == id).findFirst().orElseThrow();
    }

    public User register(String email, String password, String name) {
        users.forEach((user) -> {
            if (user.getEmail().equalsIgnoreCase(email)) {
                throw new RuntimeException("email exist.");
            }
        });
        User user = new User(users.stream().mapToLong(u -> u.getId()).max().getAsLong(), email, password, name);
        users.add(user);
        mailService.sendRegistrationMail(user);
        return user;
    }
}
